package com.pkk.penguin.frame.know.java.interview.year2021.atguigu_20210226.algorithm;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import lombok.SneakyThrows;

/**
 * 可重入锁的测试
 *
 * @author peikunkun
 * @version V1.0
 * @date 2021-02-26 16:39
 **/
public class ReentrantLockTest {


  public synchronized void m1() {
    System.out.println("m1开始执行");
    m2();
  }


  public synchronized void m2() {
    System.out.println("m2开始执行");
    m3();
  }

  public synchronized void m3() {
    System.out.println("m3开始执行");
  }

  //-----------------------------------------

  public static void lockSimple() {
    final ReentrantLock reentrantLock = new ReentrantLock();
    Condition condition = reentrantLock.newCondition();
    try {
      reentrantLock.lock();
      reentrantLock.lock();
      System.out.println("1执行了");
      try {
        reentrantLock.lock();
        System.out.println("2执行了");
      } finally {
        reentrantLock.unlock();
      }
    } finally {
      reentrantLock.unlock();
    }
  }


  private static final BlockingQueue workQueue = new ArrayBlockingQueue(30, true);
  static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 2, 60, TimeUnit.SECONDS, workQueue,
      new ThreadPoolExecutor.AbortPolicy());


  public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
    lock();
    System.out.println("主方法结束");
  }


  public static void syn() {
    final ReentrantLockTest reentrantLockTest = new ReentrantLockTest();
    CyclicBarrier cyclicBarrier = new CyclicBarrier(1);
    threadPoolExecutor.execute(new Runnable() {
      @SneakyThrows
      @Override
      public void run() {
        reentrantLockTest.m1();
        cyclicBarrier.await();
        System.out.println("执行完毕");

      }
    });
    threadPoolExecutor.shutdown();
  }


  public static void lock() throws InterruptedException {

    Semaphore semaphore = new Semaphore(2, true);
    threadPoolExecutor.execute(new Runnable() {
      @Override
      public void run() {
        try {
          lockSimple();
        } finally {
          semaphore.release();
        }
      }
    });

    threadPoolExecutor.execute(new Runnable() {
      @Override
      public void run() {
        try {
          lockSimple();
        } finally {
          semaphore.release();
        }
      }
    });

    threadPoolExecutor.shutdown();
  }


}
